﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Configuration;
using System.IO;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

using DotNetNuke.Common.Utilities;
using DotNetNuke.Entities.Users;
using DotNetNuke.Entities.Portals;
using DotNetNuke.Services.Exceptions;

using CharityGamesOnline.Modules.Common;
using ISGPayment;

namespace CharityGamesOnline.Modules.Account
{
    public partial class PaymentReturn : CGOBase
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            string remote_ip = Request.ServerVariables["REMOTE_HOST"];
            string remote_host = string.Empty;                       
            try
            {
                remote_host = System.Net.Dns.GetHostEntry(remote_ip).HostName.ToLower();
            }
            catch
            {
            }

            if (!Null.IsNull(Settings["RemoteHost"]) 
                && remote_host == Settings["RemoteHost"].ToString().ToLower()
               )
            {
                
                PaymentController ctrlPayment = new PaymentController();
                AccountController ctrlAccount = new AccountController();
                ClientISGReturnProcess process = null;
                try
                {
                    process = new ClientISGReturnProcess(Request.Form);
                    if (process.AppID == ConfigurationManager.AppSettings["ISGAppID"])
                    {
                        PaymentInfo objPayment = ctrlPayment.GetPayment(PortalId, Int32.Parse(process.TransactionID));

                        if (objPayment != null && objPayment.StatusID != (int)PaymentInfo.STATUS.Completed)
                        {
                            decimal amount = 0;

                            #region Update Payment
                            if (process.Approved || process.Test_Approved)
                            {
                                objPayment.StatusID = (int)PaymentInfo.STATUS.Completed;
                                amount = objPayment.Amount;
                            }
                            if (process.Refund)
                            {
                                objPayment.StatusID = (int)PaymentInfo.STATUS.Refund;
                                amount = 0 - objPayment.Amount;
                            }
                            ctrlPayment.SavePayment(objPayment);
                            #endregion

                            #region Update Account
                            AccountInfo objAccount = ctrlAccount.GetAccount(PortalId, objPayment.UserID);
                            if (objAccount == null)
                            {
                                objAccount = new AccountInfo();
                                objAccount.PortalID = PortalSettings.Current.PortalId;
                                objAccount.UserID = objPayment.UserID;
                                objAccount.Token = 0;
                            }
                            objAccount.Token += amount;
                            ctrlAccount.SaveAccount(objAccount);
                            #endregion

                            #region Update Account Log
                            AccountLogInfo objLog = new AccountLogInfo(objAccount);
                            objLog.PaymentID = objPayment.PaymentID;
                            if (process.Approved)
                            {
                                objLog.Comment = "Recharge";
                            }
                            if (process.Test_Approved)
                            {
                                objLog.Comment = "Recharge Test";
                            }
                            if (process.Refund)
                            {
                                objLog.Comment = "Refund";
                            }
                            ctrlAccount.SaveAccountLog(objLog);
                            #endregion
                        }
                    }
                }
                catch (Exception ex)
                {
                    StreamWriter errorLog = new StreamWriter(HttpContext.Current.Server.MapPath(".") + "\\PAY_RETURN_ERR.log", true);
                    errorLog.WriteLine(DateTime.Now.ToString());
                    if (process != null)
                    {
                        errorLog.WriteLine(string.Format("PaymentID:{0}", process.TransactionID));
                    }
                    errorLog.WriteLine("Exception Message:");
                    errorLog.WriteLine(ex.Message);
                    errorLog.WriteLine("Exception Trace:");
                    errorLog.WriteLine(ex.StackTrace);
                    errorLog.Close();
                }
                finally
                {
                    PaymentLogInfo objLog = new PaymentLogInfo();
                    if (process != null)
                    {
                        objLog.PaymentID = Int32.Parse(process.TransactionID);
                        objLog.AppID = process.AppID;
                        objLog.ApprovalCode = process.ApprovalCode;
                        objLog.IsTest = process.IsTest;
                        objLog.PageNumber = process.PageNumber;
                        objLog.ProductKey = process.Products[0].Key;
                        objLog.ProductQuantity = process.Products[0].Quantity;
                        objLog.ReceiptNumber = process.ReceiptNumber;
                        objLog.SalesOrderNumber = process.SalesOrderNumber;
                        objLog.TransactionID = process.TransactionID;
                        objLog.TransType = process.TransType;

                        ctrlPayment.SavePaymentLog(objLog);
                    }
                }
            }
        }
    }
}